package com.prawn.user.controller;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.jsonwebtoken.Claims;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.prawn.user.pojo.User;
import com.prawn.user.service.UserService;

import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import util.JwtUtil;
import util.NullAttributeUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 控制器层
 * @author Administrator
 *
 */
@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;

	@Autowired
	private JwtUtil jwtUtil;

	@RequestMapping(value = "/login",method = RequestMethod.POST)
	public Result login(@RequestBody User user) {
		//用户登录
		User adminLogin = userService.login(user);
		if (adminLogin == null)  {
			return new Result(false,StatusCode.LOGINERROR,"登录失败");
		}
		//权限控制，生成访问网站服务的令牌 (用户id,用户名，权限信息)
		String jwtToken = jwtUtil.createJWT(adminLogin.getId(), adminLogin.getLoginName(), "admin");
		Map<String,Object> map = new HashMap<>();
		map.put("token",jwtToken);
		map.put("roles","admin");
		return new Result(true,StatusCode.OK,"登录成功",map);
	}

	/**
	 * 根据token查询用户信息
	 * @return
	 */
	@RequestMapping(value = "/info",method = RequestMethod.GET)
	public Result findUserByToken(HttpServletRequest request) {
		String usertoken = (String) request.getAttribute("claims_user");
		try {
			Claims claims = jwtUtil.parseJWT(usertoken);
			String userId = claims.getId();
			User user = userService.findById(userId);
			return new Result(true,StatusCode.OK,"查询成功",user);
		} catch (Exception e) {
			return new Result(false,StatusCode.ERROR,"登录信息已过期");
		}
	}

	/**
	 * 查询全部数据
	 * @return
	 */
	@RequestMapping(method= RequestMethod.GET)
	public Result findAll(){
		return new Result(true,StatusCode.OK,"查询成功",userService.findAll());
	}
	
	/**
	 * 根据ID查询
	 * @param id ID
	 * @return
	 */
	@RequestMapping(value="/{id}",method= RequestMethod.GET)
	public Result findById(@PathVariable String id){
		return new Result(true,StatusCode.OK,"查询成功",userService.findById(id));
	}


	/**
	 * 分页+多条件查询
	 * @param searchMap 查询条件封装
	 * @param page 页码
	 * @param size 页大小
	 * @return 分页结果
	 */
	@RequestMapping(value="/search/{page}/{size}",method=RequestMethod.POST)
	public Result findSearch(@RequestBody Map searchMap , @PathVariable int page, @PathVariable int size){
		Page<User> pageList = userService.findSearch(searchMap, page, size);
		return  new Result(true,StatusCode.OK,"查询成功",  new PageResult<User>(pageList.getTotalElements(), pageList.getContent()) );
	}

	/**
     * 根据条件查询
     * @param searchMap
     * @return
     */
    @RequestMapping(value="/search",method = RequestMethod.POST)
    public Result findSearch( @RequestBody Map searchMap){
        return new Result(true,StatusCode.OK,"查询成功",userService.findSearch(searchMap));
    }
	
	/**
	 * 增加
	 * @param user
	 */
	@RequestMapping(method=RequestMethod.POST)
	public Result add(@RequestBody User user  ){
		user.setCreateDate(new Date());
		user.setUpdateDate(new Date());
		userService.add(user);
		return new Result(true,StatusCode.OK,"增加成功");
	}
	
	/**
	 * 修改
	 * @param user
	 */
	@RequestMapping(value="/{id}",method= RequestMethod.PUT)
	public Result update(@RequestBody User user, @PathVariable String id ){
		user.setId(id);
		user.setUpdateDate(new Date());
		//不修改null值
		User targetUser = userService.findById(user.getId());
		BeanUtils.copyProperties(user,targetUser, NullAttributeUtils.getNullPropertyNames(user));
		userService.update(targetUser);
		return new Result(true,StatusCode.OK,"修改成功");
	}
	
	/**
	 * 删除
	 * @param id
	 */
	@RequestMapping(value="/{id}",method= RequestMethod.DELETE)
	public Result delete(@PathVariable String id ,HttpServletRequest request){
		//验证删除权限
		String claims = (String) request.getAttribute("claims_admin");
		if (claims == null || "".equals(claims)) {
			return new Result(false,StatusCode.ACCESSERROR,"无权访问");
		}
		userService.deleteById(id);
		return new Result(true,StatusCode.OK,"删除成功");
	}
	
}
